from flask import Blueprint, jsonify, send_file
from app.models.dataset import Dataset

bp = Blueprint('export', __name__, url_prefix='/api/export')

@bp.route('/cleaned/<int:dataset_id>', methods=['GET'])
def export_cleaned_dataset(dataset_id):
    """导出数据集文件，优先导出清洗后的文件，否则导出原始文件"""
    dataset = Dataset.query.get(dataset_id)
    if not dataset:
        return jsonify({'error': '数据集不存在'}), 404
    file_path = getattr(dataset, 'cleaned_file_path', None) or dataset.file_path
    if not file_path:
        return jsonify({'error': '数据集文件不存在'}), 400
    try:
        download_name = f'cleaned_{getattr(dataset, "name", "exported_dataset")}.csv'
        return send_file(file_path, as_attachment=True, download_name=download_name, mimetype='text/csv')
    except Exception as e:
        return jsonify({'error': f'导出失败: {str(e)}'}), 500
